﻿using Infrastructure.AggregateBase;
using Microsoft.EntityFrameworkCore;
using System;

namespace Infrastructure.RepositoryBase
{
    public abstract class AbstractRepository<TEntity> : IRepository<TEntity> where TEntity : AggregateRoot
    {
        public Guid guid = Guid.NewGuid();
        public DbContext dbContext { get; set; }
        public System.Linq.IQueryable<TEntity> Entities => dbContext.Set<TEntity>();

        public void Delete(object id)
        {
            var entity = dbContext.Find<TEntity>(id);
            entity.IsDelete = true;

            var dbEntity = dbContext.Entry(entity);
            dbEntity.State = EntityState.Modified;
            
        }

        public void Delete(TEntity entity)
        {
            entity.IsDelete = true;

            var dbEntity = dbContext.Entry(entity);
            dbEntity.State = EntityState.Modified;
        }

        public void Delete(System.Collections.Generic.IEnumerable<TEntity> entities)
        {
            foreach (var item in entities)
            {
                Delete(item);
            }
        }

        public TEntity GetByKey(object key)
        {
            var entity = dbContext.Find<TEntity>(key);

            return entity;
        }

        public TEntity Insert(TEntity entity)
        {
            var dbEntity = dbContext.Entry(entity);
            dbEntity.State = EntityState.Added;

            return dbEntity.Entity;
        }

        public void Insert(System.Collections.Generic.IEnumerable<TEntity> entities)
        {
            foreach (var item in entities)
            {
                Insert(item);
            }
        }

        public void Update(TEntity entity)
        {
            var dbEntity = dbContext.Entry(entity);
            dbEntity.Entity.UT = DateTime.Now;
            dbEntity.State = EntityState.Modified;
        }
    }
}
